import { inject, onMounted, ref } from "vue"
import { mapStore } from "@/stores/counter"
import axios from "axios"
import { getGDP } from "@/models/getGDPHttp"
export const extra = () => {
    const store = mapStore()
    let map
    let scene
    let data, geojson_height, popup, gdpData, geojson_gdp
    let citiesPolygon = []
    let high_data = {
        type: "FeatureCollection",
        features: []
    }
    const popupTop = ref(0)
    const popupLeft = ref(0)
    const gdpYear = ref()
    const gdpCity = ref()
    const gdp = ref()

    onMounted(async () => {
        map = inject('$map')
        scene = inject('$scene')
        const res = await axios.get('/src/source/海拔/城市海拔.csv')
        const lines = res.split('\n')
        data = lines.slice(1).map(item => {
            const value = item.split(',')
            return {
                province: value[2],
                city: value[3],
                height: parseInt(value[7]),
                lng: parseFloat(value[9]),
                lat: parseFloat(value[10])
            }
        })

        // data.forEach(async (item) => {
        //     const res = await axios.get(`https://geo.datav.aliyun.com/areas_v3/bound/${item.adcode}.json`)

        //     citiesPolygon.push({
        //         province: item.province,
        //         city: item.city,
        //         height: item.height,
        //         coordinates: res.features[0].geometry.coordinates
        //     })
        // })

        const result = await getGDP(store.selectedYear)
        const gdpLines = result.split('\n')
        gdpData = gdpLines.slice(1).map(item => {
            const value = item.split(',')
            return {
                year: value[0],
                city: value[1],
                adcode: value[2],
                gdp: parseInt(value[6]),
            }
        })

        gdpData.forEach(async (item) => {
            const res = await axios.get(`https://geo.datav.aliyun.com/areas_v3/bound/${item.adcode}.json`)
            citiesPolygon.push({
                city: item.city,
                gdp: item.gdp,
                year: item.year,
                coordinates: res.features[0].geometry.coordinates
            })
        })
    })

    const citiesHeight = () => {
        if (scene.getLayer() != 0) {
            scene.removeAllLayer()
        }
        geojson_height = {
            type: 'FeatureCollection',
            features: data.map(item => ({
                type: 'Feature',
                geometry: {
                    type: 'Point',
                    coordinates: [item.lng, item.lat]
                },
                properties: {
                    height: item.height,
                    province: item.province,
                    city: item.city
                }
            }))
        };



        // const layer = new L7.HeatmapLayer({})
        //     .source(geojson_height, {
        //         transforms: [
        //             {
        //                 type: 'hexagon',
        //                 size: 1000,  // 尝试调整大小
        //                 field: 'height',
        //                 method: 'sum',
        //             },
        //         ],
        //     })
        //     .size('sum', (sum) => {
        //         return sum * 100;
        //     })
        //     .shape('hexagonColumn')
        //     .style({
        //         coverage: 0.8,
        //         angle: 0,
        //     })
        //     .color('#ff2d51');

        // scene.addLayer(layer);

        const pointLayer = new L7.PointLayer({ depth: false })
            .source(geojson_height)
            .animate(true)
            .active(true)
            .shape('height', ['cylinder', 'triangleColumn', 'hexagonColumn', 'squareColumn'])
            .size('height', function (level) {
                return [3, 3, level / 20];
            })
            .color('height', ['#739DFF', '#61FCBF', '#FFDE74', '#FF896F']);

        pointLayer.on('mousemove', (e) => {
            popup = new L7.Popup({
                offsets: [0, 0],
                closeButton: false,
            })
                .setLnglat(e.lngLat)
                .setHTML(`<span>地区 : ${e.feature.properties.province}</br>城市 : ${e.feature.properties.city}</br> 海拔 : ${e.feature.properties.height}米</span>`);
            scene.addPopup(popup);
        });
        pointLayer.on('mouseout', () => {
            scene.removePopup(popup)
        })

        scene.addLayer(pointLayer);

    }

    const citiesGDP = async () => {
        const newYear = store.selectedYear
        // 清除图层
        const layers = map.getStyle().layers
        const arr_gdpLayer = layers.filter(item => item.id.startsWith('gdp_map'))
        const arr_high_layer = layers.filter(item => item.id.startsWith('high-layer'))
        arr_gdpLayer.forEach(item => {
            map.removeLayer(item.id)
        })
        arr_high_layer.forEach(item => {
            map.removeLayer(item.id)
        })

        store.isGDP = true
        store.isTemp = false
        store.isRainy = false
        store.isSun = false
        store.isPM = false
        store.isClick = true

        if (newYear == store.selectedYear) {
            const result = await getGDP(newYear)
            const gdpLines = result.split('\n')
            gdpData = gdpLines.slice(1).map(item => {
                const value = item.split(',')
                return {
                    year: value[0],
                    city: value[1],
                    adcode: value[2],
                    gdp: parseInt(value[6]),
                }
            })

            // gdpData.forEach(async (item) => {
            //     const res = await axios.get(`https://geo.datav.aliyun.com/areas_v3/bound/${item.adcode}.json`)
            //     citiesPolygon.push({
            //         city: item.city,
            //         gdp: item.gdp,
            //         year: item.year,
            //         coordinates: res.features[0].geometry.coordinates
            //     })
            // })
            // 使用 map 和 Promise.all 处理异步请求
            const citiesPolygonPromises = gdpData.map(async (item) => {
                try {
                    const response = await axios.get(`https://geo.datav.aliyun.com/areas_v3/bound/${item.adcode}.json`);
                    return {
                        city: item.city,
                        gdp: item.gdp,
                        year: item.year,
                        coordinates: response.features[0].geometry.coordinates
                    };
                } catch (error) {
                    console.error(`Error fetching data for adcode ${item.adcode}:`, error);
                    return null; // 或者处理错误的其他方式
                }
            });
            citiesPolygon = await Promise.all(citiesPolygonPromises);


            // 转为geojson
            geojson_gdp = {
                type: 'FeatureCollection',
                features: citiesPolygon.filter(item => item !== null).map(item => ({
                    type: "Feature",
                    geometry: {
                        type: "Polygon",
                        coordinates: item.coordinates.flat()
                    },
                    properties: {
                        city: item.city,
                        gdp: item.gdp,
                        year: item.year
                    }
                }))
            }

            // // 添加到地图
            map.addLayer({
                id: 'gdp_map' + Date.now(),
                source: {
                    type: "geojson",
                    data: geojson_gdp
                },
                type: 'fill',
                paint: {
                    'fill-color': [
                        'step',
                        ['get', 'gdp'], // 使用属性值作为输入
                        '#f7fbff', // 低值颜色
                        1000, '#3182bd', // 10000以下使用这颜色
                        5000, '#9ecae1', // 50000以下使用这颜色
                        10000, '#ff2d51' // 100000以上使用这颜色
                    ],
                    'fill-opacity': 0.5
                }
            })
            // 添加轮廓线
            map.addLayer({
                id: 'gdp_map_line' + Date.now(),
                source: {
                    type: "geojson",
                    data: geojson_gdp
                },
                type: "line",
                paint: {
                    'line-color': 'pink',
                    'line-width': 1
                }
            })

            let source = 'high-layer_source' + Date.now()
            map.addSource(source, {
                type: 'geojson',
                data: high_data
            })

            map.addLayer({
                id: 'high-layer' + Date.now(),
                source: source,
                type: 'fill',
                paint: {
                    'fill-opacity': 0.5,
                    'fill-color': 'blue'
                }
            })

            let layer = map.getStyle().layers.reverse()[2].id

            map.on('click', layer, (evt) => {
                // 点击前清除图层
                store.isMouseClick = true
                high_data.features = []
                let high_source = map.getSource(source)
                high_data.features.push(evt.features[0])
                high_source.setData(high_data)
                // 弹窗
                store.gdpYear = evt.features[0].properties.year
                store.gdpCity = evt.features[0].properties.city
                gdp.value = evt.features[0].properties.gdp
                store.gdp = evt.features[0].properties.gdp
                const coordinates = evt.lngLat
                const pos = map.project(coordinates)
                popupLeft.value = pos.x
                popupTop.value = pos.y
            })
        }
    }

    const loveCity = async () => {
        store.WeightList = [
            { pm: null },
            { temp: null },
            { rainy: null },
            { sun: null },
            { height: null },
            { gdp: null }
        ]
        store.pmValue = 0;
        store.tempValue = 0;
        store.rainyValue = 0;
        store.sunValue = 0;
        store.heightValue = 0;
        store.gdpValue = 0;
        store.isLove = true
    }

    const renderGDP = () => {
        citiesGDP()
    }

    return {
        citiesHeight,
        citiesGDP,
        loveCity,
        renderGDP,
        popupTop,
        popupLeft,

    }
}